//导入所需模块
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
//导入路由模块
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
//导入书籍路由
const booksRouter = require("./routes/books");
//导入书架路由
const bookshelvesRouter = require("./routes/bookshelves");
//应用层中间件
var app = express();
// 导入Session模块
const session = require("express-session");
// 导入Session存储支持模块SQLite
const SQLiteStore = require("connect-sqlite3")(session);
// 导入Swagger-ui-express模块
const swaggerUi = require("swagger-ui-express");
// 导入Swagger-jsdoc模块
const swaggerJsdoc = require("swagger-jsdoc");
//导入初始化数据库中间件
const initSqliteDB = require("./controller/init");
// 中间件： Swagger
const options = {
  definition: {
    openapi: "3.0.0",
    info: {
        titile: "我的藏书房接口",
        version: "1.0.0",
    },
  },
  apis: [path.join(__dirname, "./routes/*.js")],
};
 
const openapiSpecification = swaggerJsdoc(options);
///
app.use(
  session({
    secret: "sdfsdfsf@#@$234", //session的salt
    resave: false, //session工作方式：session是否重新保存
    saveUninitialized: false, //session工作方式：未初始化的session是否保存
    cookie: { maxAge: 7 * 24 * 60 * 60 * 1000 }, // sessionID在客户端cookie中保存1周
    store: new SQLiteStore({
      dir: "./data",
      db: "mylibrary.db",
    }),
  })
);
app.use("/dev-api", swaggerUi.serve, swaggerUi.setup(openapiSpecification));
//中间件：数据库初始化
app.use(initSqliteDB());
app.use(logger('dev'));
app.use(express.json());
//导入session支持
//url
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//书籍路由
app.use("/books",booksRouter);
//书架路由
app.use("/bookshelves",bookshelvesRouter);
app.use("/", indexRouter);
app.use("/users", usersRouter);
/**
 * Express中的Session支持
 * 1. npm install express-sesion connect-sqlite3
 * 2. 导入模块
 * 3. 使用Session中间件
 * 4. Session存储：SQLiteStore
 */
 

module.exports = app;
